#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import io
import sys
import gzip
import mrget
import shutil
import subprocess
import lxml.html
import urllib.request


def findKernelVersion(url, typename):
    with urllib.request.urlopen(url, timeout=60) as resp:
        if resp.info().get('Content-Encoding') is None:
            fakef = resp
        elif resp.info().get('Content-Encoding') == 'gzip':
            fakef = io.BytesIO(resp.read())
            fakef = gzip.GzipFile(fileobj=fakef)
        else:
            assert False
        root = lxml.html.parse(fakef)

        td = root.xpath(".//td[text()='%s:']" % (typename))[0]
        td = td.getnext()
        while len(td) > 0:
            td = td[0]
        return td.text


def download(version, kernelFile):
    subdir = None
    for i in range(3, 9):
        if version.startswith(str(i)):
            subdir = "v%d.x" % (i)
    assert subdir is not None

    urlKernelFile = os.path.join(subdir, kernelFile)
    url = mrget.target_urls("mirror://kernel-org-pub/linux/kernel/%s" % (urlKernelFile), filter_key=lambda x: x["protocol"] in ["http", "https", "ftp"])[0]
    subprocess.run(["wget", "-c", url])


def forceDelete(path):
    if os.path.islink(path):
        os.remove(path)
    elif os.path.isfile(path):
        os.remove(path)
    elif os.path.isdir(path):
        shutil.rmtree(path)
    elif os.path.lexists(path):
        os.remove(path)             # other type of file, such as device node
    else:
        pass                        # path does not exist, do nothing


if __name__ == "__main__":
    ktype = "stable"
    # if len(sys.argv) > 1:
    #     assert sys.argv[1] in ["stable", "mainline", "longterm"]
    #     ktype = sys.argv[1]

    version = "6.5.9"
    # version = "5.18.5"
    # url = mrget.target_urls("mirror://kernel-org")[0]
    # version = findKernelVersion(url, ktype)

    kernelFile = "linux-%s.tar.xz" % (version)
    fullKernelFile = os.path.join("/var/cache/bbki/distfiles", kernelFile)
    if not os.path.exists(fullKernelFile):
        download(version, kernelFile)
        fullKernelFile = kernelFile

    kernelDir = kernelFile.replace(".tar.xz", "")
    forceDelete(kernelDir)
    subprocess.run(["tar", "-xJf", fullKernelFile])
    assert os.path.exists(kernelDir)
